//
// Created by pangy on 2025/5/11.
//
#include "Union.h"

/**
 * 并集算法, 合并到线性表A中
 * @param La 线性表A
 * @param Lb 线性表B
 */
void Union(SqList* La, SqList Lb) {
    int La_len, Lb_len;
    ElemType e;
    La_len = La->length;
    Lb_len = Lb.length;

    for (int i = 1; i <= Lb_len; ++i) {
        // 获取表Lb中第i个数据元素赋给e
        GetElem(Lb, i, &e);
        // 进行比较
        if (!LocateElem(*La, e, equal)) {
            ListInsert(La, ++La_len, e);
        }
    }
}

/**
 * 归并线性表La,Lb到Lc
 * La/Lb的元素按值非递减
 * @param La
 * @param Lb
 * @param Lc
 */
void MergeList(SqList La, SqList Lb, SqList* Lc) {
    ElemType *pa, *pb, *pc;
    ElemType *pa_last, *pb_last;

    pa = La.elem;
    pb = Lb.elem;

    Lc->listSize = Lc->length = La.length + Lb.length;
    // 给表Lc分配内存空间
    pc = Lc->elem = (ElemType*) malloc(Lc->listSize * sizeof(ElemType));

    if (!Lc->elem) {
        // 内存空间不足
        exit(OVERFLOW);
    }

    // 表尾元素
    pa_last = La.elem + La.length - 1;
    pb_last = Lb.elem + Lb.length - 1;

    while (pa <= pa_last && pb <= pb_last) {
        if (*pa <= *pb) {
            *pc++ = *pa++;
        } else {
            *pc++ = *pb++;
        }
    }
    while (pa <= pa_last) {
        *pc++ = *pa++;
    }
    while (pb <= pb_last) {
        *pc++ = *pb++;
    }
}